<?php

namespace Home\Model;
use Think\Model;

class ServicesModel extends Model {
	//根据服务编号，获取该服务api详情及api授权信息
	public function getApiinfosWithServiceid($service_id){
		if(empty($service_id) || !is_numeric($service_id)) return null;

		$sql  = "select s.service_id,s.service_name services_name,s.service_name_en services_name_en,";
		$sql .= "s.service_introduction,s.service_logo,FROM_UNIXTIME((s.update_time),'%Y-%m-%d %T') service_update_time,";
		$sql .= "ifnull(api.api_id,0) api_id,ifnull(api.api_name,'该服务无API') api_name,api.api_name_en";

		$sql .= " from  dmp_services s left join dmp_service_apis api on api.service_id=s.service_id ";

		$sql .=" where s.service_id=$service_id";
		$list = $this->query($sql);

		return $list;
	}

	//获取分类下服务列表信息（分页，数量，排序规则）
	public function getListWithCategory($category_id,$second_cid=0,$order_type = 1,$page = 1,$pagesize = 20){
		$key = md5("servicemodellist_with_category_".$category_id."_".$order_type);

		if(session( md5('37degree_redis') ) === true){//清楚缓存
            S($key,null);
            $all_list = false;
        }else{
            $all_list = S($key);
        }
        
		if($all_list===false){
			//默认排序，按照服务英文名称正向排；按照调用次数倒排；（注意，服务状态，是否有上线api）
			switch($order_type){
				case 2:
					$order_string = " order by s.call_num desc ";
					break;
				default:
					$order_string = " order by s.service_name_en asc ";
					break;
			}

			//todo 缓存
			
			$count_sql = "select s.service_name,s.service_name_en,s.call_num,s.service_publisher,count(image.service_id) num,s.service_logo,s.service_introduction,s.uid,u.auth_type,s.service_id,ifnull(least(min(image.min_price),if(image.api_is_charge=0,0,99999999) ),0) price,group_concat(DISTINCT tag.name) tag_string "; 
			$count_sql .=	" from dmp_services s left join dmp_service_apis_image image on image.service_id=s.service_id left join dmp_service_tag ser_tag on ser_tag.service_id=s.service_id left join dmp_tag tag on tag.id=ser_tag.tag_id LEFT JOIN dmp_users u on u.id=image.uid ";
			$count_sql .=" where s.service_status=1 and s.service_enable=0 and image.api_status=1 and image.api_auth_status=2 "; 
			if($category_id && is_numeric($category_id)) $count_sql .=" and s.category_id= ".$category_id ;
			if($second_cid && is_numeric($second_cid)) $count_sql .=" and s.children_category_id= ".$second_cid ;
			
			$count_sql .=" group by image.service_id HAVING num >0 ";
			$sql = $count_sql.$order_string;
			$all_list = $this->query($sql);
			
			S($key,$all_list,3600);

		}
		
		$total_num = count($all_list);

		$start = ($page-1)*$pagesize;
		$list = array_slice($all_list, $start, $pagesize);
		$data['total_num'] = $total_num;
		$data['list'] = $list;
		return $data;
	}

	// 获取用户服务数据
	public function getServiceWithRelatedUser($uid = null,$limit = 5){
		if(empty($uid)) return null;

		$where = array('service_status'=>1,'uid'=>$uid);//已发布
		return $list = $this->where($where)->select();
	}

}

?>